/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.business.domain.Pgjl;
import me.zhengjie.pdf.make.MakePdf;
import me.zhengjie.pdf.vo.PDFVO;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.PgjlRepository;
import me.zhengjie.business.service.PgjlService;
import me.zhengjie.business.service.dto.PgjlDto;
import me.zhengjie.business.service.dto.PgjlQueryCriteria;
import me.zhengjie.business.service.mapstruct.PgjlMapper;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2025-04-28
**/
@Service
@RequiredArgsConstructor
public class PgjlServiceImpl implements PgjlService {

    private final PgjlRepository pgjlRepository;
    private final PgjlMapper pgjlMapper;

    @Override
    public Map<String,Object> queryAll(PgjlQueryCriteria criteria, Pageable pageable){
        Page<Pgjl> page = pgjlRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(pgjlMapper::toDto));
    }

    @Override
    public List<PgjlDto> queryAll(PgjlQueryCriteria criteria){
        return pgjlMapper.toDto(pgjlRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PgjlDto findById(String bisPgjlId) {
        Pgjl pgjl = pgjlRepository.findById(bisPgjlId).orElseGet(Pgjl::new);
        ValidationUtil.isNull(pgjl.getBisPgjlId(),"Pgjl","bisPgjlId",bisPgjlId);
        return pgjlMapper.toDto(pgjl);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PgjlDto create(Pgjl resources) {
        resources.setBisPgjlId(IdUtil.simpleUUID()); 
        return pgjlMapper.toDto(pgjlRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Pgjl resources) {
        Pgjl pgjl = pgjlRepository.findById(resources.getBisPgjlId()).orElseGet(Pgjl::new);
        ValidationUtil.isNull( pgjl.getBisPgjlId(),"Pgjl","id",resources.getBisPgjlId());
        pgjl.copy(resources);
        pgjlRepository.save(pgjl);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisPgjlId : ids) {
            pgjlRepository.deleteById(bisPgjlId);
        }
    }

    @Override
    public void download(List<PgjlDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PgjlDto pgjl : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public File getLatestGeneratedFile(String bisPgjlId) {
        PgjlDto pgjlDto = this.findById(bisPgjlId);

        MakePdf makePdf = new MakePdf();
        JSONObject freeLanceObject = new JSONObject();
        freeLanceObject.put("name", pgjlDto.getXm());
        freeLanceObject.put("idcard", pgjlDto.getSfz());
        freeLanceObject.put("applicant", pgjlDto.getSqr());
        freeLanceObject.put("assesslv", pgjlDto.getSndj());
        freeLanceObject.put("sftg", pgjlDto.getIsfh());
        freeLanceObject.put("assessdate", pgjlDto.getPgjl());
        freeLanceObject.put("C1_1", pgjlDto.getC01());
        freeLanceObject.put("C1_2", pgjlDto.getC02());
        freeLanceObject.put("C1_3", pgjlDto.getC03());
        freeLanceObject.put("C1_4", pgjlDto.getC04());
        freeLanceObject.put("C1_5", pgjlDto.getC05());
        freeLanceObject.put("C1_6", pgjlDto.getC06());
        freeLanceObject.put("C1_7", pgjlDto.getC07());
        freeLanceObject.put("C1_8", pgjlDto.getC08());
        freeLanceObject.put("C1_9", pgjlDto.getC09());
        freeLanceObject.put("C1_10", pgjlDto.getC10());
        freeLanceObject.put("C1", pgjlDto.getC1());
        freeLanceObject.put("C1_ASSESSOR_1", pgjlDto.getPgr());
        freeLanceObject.put("C1_ASSESSOR_2", "");
        freeLanceObject.put("C2_11", pgjlDto.getC11());
        freeLanceObject.put("C2_12", pgjlDto.getC12());
        freeLanceObject.put("C2_13", pgjlDto.getC13());
        freeLanceObject.put("C2_14", pgjlDto.getC14());
        freeLanceObject.put("C2", pgjlDto.getC2());
        freeLanceObject.put("C2_ASSESSOR_1", pgjlDto.getPgr());
        freeLanceObject.put("C2_ASSESSOR_2", "");
        freeLanceObject.put("C3_15", pgjlDto.getC15());
        freeLanceObject.put("C3_16", pgjlDto.getC16());
        freeLanceObject.put("C3_17", pgjlDto.getC17());
        freeLanceObject.put("C3", pgjlDto.getC3());
        freeLanceObject.put("C3_ASSESSOR_1", pgjlDto.getPgr());
        freeLanceObject.put("C3_ASSESSOR_2", "");

        List<PDFVO> list2 = makePdf.getCoordinate(freeLanceObject);

        String datetime = pgjlDto.getJgbm()+"-"+pgjlDto.getPgjl()+"-"+pgjlDto.getPgr()+"-"+pgjlDto.getXm()+"-"+pgjlDto.getSfz();
        String pdfName = datetime+".pdf";

        File fileDemo = new File("F:\\WPSCloud\\评估结论书和评估表.pdf");//样例文件 固定地址存放
        File fileFont = new File("C:\\eladmin\\file\\"+"songti.ttf");//字体 固定地址存放


        String datetime1 = cn.hutool.core.date.DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        String folderPath = "F:\\WPSCloud\\"+datetime1;
        File folder = new File(folderPath);

        // 检查文件夹是否存在
        if (!folder.exists()) {
            // 创建文件夹
            boolean created = folder.mkdirs(); // 使用mkdirs()确保父目录也被创建
            if (created) {
                System.out.println("文件夹已成功创建: " + folderPath);
            } else {
                System.out.println("无法创建文件夹: " + folderPath);
            }
        } else {
            System.out.println("文件夹已存在: " + folderPath);
        }


        File fileTarget = new File(folderPath+"\\" +pdfName);//目标文件 地址可以直接创建在临时目录
        try{
            Files.copy(fileDemo.toPath(), fileTarget.toPath());//样例文件内容 复制到 目标文件
            PDDocument template = PDDocument.load(fileTarget);//对目标文件进行操作
            //遍历添加文本
            for (PDFVO pdfvo : list2){
                PDPage page = template.getPage(pdfvo.getPage());
                PDPageContentStream contentStream = new PDPageContentStream(template, page, PDPageContentStream.AppendMode.APPEND, false, false);
                PDType0Font font = PDType0Font.load(template, fileFont);
                contentStream.beginText();
                contentStream.setFont(font, 14);
                contentStream.newLineAtOffset(pdfvo.getTx(), pdfvo.getTy());//位置
                contentStream.showText(pdfvo.getValue());//值
                contentStream.endText();
                contentStream.close();
            }
            //写入权限
            fileTarget.setWritable(true);
            // 保存PDF文件
            template.save(fileTarget);
            template.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileTarget;
    }
}